package com.xuzy.x808.server;

import com.xuzy.x808.server.handler.ServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class JT808ChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    @Qualifier("businessGroup")
    private EventExecutorGroup businessGroup;

    @Autowired
    private ServerHandler serverHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 解决粘包问题（使用特殊字符作为分消息分隔符，分隔符之间的报文为一个完整的消息）
        ByteBuf delimiter = Unpooled.buffer(1);
        delimiter.writeByte(0x7E);
        pipeline.addLast(new DelimiterBasedFrameDecoder(1024, true, delimiter));

        pipeline.addLast(new IdleStateHandler(10, 0, 0, TimeUnit.MINUTES));

        pipeline.addLast(businessGroup, serverHandler);
    }
}
